<?php

/**
 * This is the model class for table "Rule".
 *
 * The followings are the available columns in table 'Rule':
 * @property string $id
 * @property integer $gid
 * @property integer $sid
 * @property string $fullcontent
 * @property string $rulecomment
 * @property string $categoryId
 * @property string $revision
 * @property string $ruleClass
 *
 * The followings are the available model relations:
 * @property RuleCategory $category
 */
class Rule extends CActiveRecord
{
	private $originContent = NULL;
	public function setOriginContent($content) {
		$this->originContent = $content;
	}
	
	public function getColoredCode() {
		$highlighter = new CTextHighlighter ();
		$highlighter->language = "php";
		return $highlighter->highlight ( $this->fullcontent );
	}
	/*
	 * (non-PHPdoc) @see CActiveRecord::beforeDelete()
	*/
	protected function beforeDelete() {
		return parent::beforeDelete ();
	}
	
	/*
	 * (non-PHPdoc) @see CActiveRecord::afterDelete()
	*/
	protected function afterDelete() {
		if (RuleFileHelper::$IS_REBUILD)
			return parent::afterDelete ();
		try {
			// RuleFileHelper::deleteRuleOnFile ( $this->originContent,
			// $this->category->category );
			RuleFileHelper::modifyRuleFile ( $this->category->category, $this->categoryId );
		} catch ( Exception $e ) {
			Yii::app ()->user->setFlash ( "error", $e->getMessage () );
			if ($e->getCode () != 1)
				return false;
		}
		$history = new RuleHistory ();
		$history->historyReason = "delete";
		$history->historyRule = $this->fullcontent;
		$history->revision = $this->revision;
		$history->rid = $this->id;
		$history->save ();
	
		$category = $this->category;
		$category->modifydate = date("Y-m-d H:i:s");
		$category->save();
	
	}
	
	/*
	 * (non-PHPdoc) @see CActiveRecord::afterSave()
	*/
	protected function afterSave() {
		if (RuleFileHelper::$IS_REBUILD)
			return parent::afterSave ();
		try {
			// RuleFileHelper::deleteRuleOnFile ( $this->originContent,
			// $this->category->category );
			RuleFileHelper::modifyRuleFile ( $this->category->category, $this->categoryId );
		} catch ( Exception $e ) {
			Yii::app ()->user->setFlash ( "error", $e->getMessage () );
			if ($e->getCode () != 1)
				return false;
		}
		$history = new RuleHistory ();
		$history->historyReason = $this->isNewRecord ? "add" : "modify";
		$history->historyRule = $this->fullcontent;
		$history->revision = $this->revision;
		$history->rid = $this->id;
		$history->save ();
	
		$category = $this->category;
		$category->modifydate = date("Y-m-d H:i:s");
		$category->save();
		
		AppConfig::increPendCnt();
	}
	
	/*
	 * (non-PHPdoc) @see CActiveRecord::beforeSave()
	*/
	protected function beforeSave() {
		if (RuleFileHelper::$IS_REBUILD)
			return parent::beforeSave ();
		$comment = $this->rulecomment;
		$comment = trim($comment);
		$arr = explode ( "\n", $comment );
		$cnt = 0;
		foreach ( $arr as $str ) {
			if ($str [0] !== '#'){
				$str = '#' . $str;
			}
			$arr[$cnt] = $str;
			$cnt++;
		}
		$comment = join ( "\n", $arr );
		$this->rulecomment = $comment;
		return parent::beforeSave ();
	}
	
	public function checkSidExists($attribute, $params) {
		if (! $this->isNewRecord && $this->sid === $this->$attribute)
			return;
		if ($this->exists ( 'sid=:id', array (
				':id' => $this->$attribute
		) ))
			$this->addError ( $attribute, "this sid already exists" );
	}
	public function checkSidFit($attribute,$params)
	{
		$str = $this->$attribute;
		$sid = RuleFileHelper::getSid($str);
		$str = trim($str);
		if(strpos($str, "\n")!==false)
			$this->addError($attribute,"the rule shoud contain only one line");
		if($sid != $this->sid)
			$this->addError($attribute,"the sid in content doesn't match");
	}
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Rule the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'Rule';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array (
				array (
						'gid, sid, fullcontent, category, revision,categoryId,ruleClass',
						'required' 
				),
				array(
					'rulecomment',
					'default',	
				),
				array (
						'gid, sid',
						'numerical',
						'integerOnly' => true 
				),
				array(
					'ruleClass',
					'length',
					'max' => 50,
				),
				array (
						'categoryId, revision',
						'length',
						'max' => 10 
				),
				array (
						'sid',
						'checkSidExists' 
				),
				array(
					'fullcontent',
					'checkSidFit'
				),
				// The following rule is used by search().
				// Please remove those attributes that should not be searched.
				array (
						'id, gid, sid, fullcontent, rulecomment, category, revision,ruleClass',
						'safe',
						'on' => 'search' 
				) 
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'category' => array(self::BELONGS_TO, 'RuleCategory', 'categoryId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'gid' => 'Gid',
			'sid' => 'Sid',
			'fullcontent' => 'Fullcontent',
			'rulecomment' => 'Rulecomment',
			'categoryId' => 'Category',
			'revision' => 'Revision',
			'ruleClass' => 'Rule Class',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($catId=NULL)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.
		$sort = new CSort ();
		$sort->attributes = array (
				'category' => array (
						'asc' => 'category',
						'desc' => 'category DESC'
				),
				'*'
		);
		$criteria = new CDbCriteria ();
		
		$criteria->with = array (
				'category'
		);
		$criteria->compare ( 'id', $this->id, true );
		$criteria->compare ( 'gid', $this->gid );
		$criteria->compare ( 'sid', $this->sid );
		$criteria->compare ( 'fullcontent', $this->fullcontent, true );
		$criteria->compare ( 'rulecomment', $this->rulecomment, true );
		if($catId === NULL)
			$criteria->compare ( 'category', $this->category, true );
		else{
			$criteria->compare ( 'categoryId', $catId);
		}
		$criteria->compare ( 'revision', $this->revision, true );
		$criteria->compare('ruleClass',$this->ruleClass,true);
		return new CActiveDataProvider ( $this, array (
				'criteria' => $criteria,
				'sort' => $sort
		) );
	}
}